package activity;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import objects.Money;
import adapter.ListviewAdapterCustom;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.viet_anh.managementmoney.R;

import database.DatabaseHandlerForApp;

public class MainActivity extends Activity {
	private EditText etMoney;
	private Button btnMoney, btnAll, btnDaily, btnMonthly;
	private ListView lvSubject;
	private BaseAdapter adapter;
	private RelativeLayout container_input, container_buttons;
	private TextView tvTotalMoney;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		overridePendingTransition(R.anim.activity_open_translate,
				R.anim.activity_close_scale);
		final DatabaseHandlerForApp db = new DatabaseHandlerForApp(
				getApplicationContext());
		// DisplayMetrics displaymetrics = getResources().getDisplayMetrics();

		tvTotalMoney = (TextView) findViewById(R.id.tvTotalMoney);
		etMoney = (EditText) findViewById(R.id.txtMoney);
		btnMoney = (Button) findViewById(R.id.btnMoney);
		btnAll = (Button) findViewById(R.id.btnAll);
		btnDaily = (Button) findViewById(R.id.btnDaily);
		btnMonthly = (Button) findViewById(R.id.btnMonthly);
		lvSubject = (ListView) findViewById(R.id.lvSubject);
		container_input = (RelativeLayout) findViewById(R.id.container_input);
		container_buttons = (RelativeLayout) findViewById(R.id.container_buttons);

		tvTotalMoney.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent in = new Intent(MainActivity.this,
						DetailTotalMoneyActivity.class);
				startActivity(in);
			}
		});

		btnMoney.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				addMoneyFromInput(db);
				setBackgroundColorForButtons(btnAll,
						getResources().getColor(R.color.normal_button),
						getResources().getColor(R.color.active_button));
				tvTotalMoney.setText(db.sumAllMoney());
			}
		});

		btnAll.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				addListview(db.getAllMoney());
				setBackgroundColorForButtons(v,
						getResources().getColor(R.color.normal_button),
						getResources().getColor(R.color.active_button));
				tvTotalMoney.setText(db.sumAllMoney());
			}
		});

		btnDaily.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				addListview(db.getMoneyByDay(getNowDate("yyyy/MM/dd")));
				setBackgroundColorForButtons(v,
						getResources().getColor(R.color.normal_button),
						getResources().getColor(R.color.active_button));
				// v.setBackgroundColor(R.color.active_button);
			}
		});

		btnMonthly.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				addListview(db.getMoneyByMonth(getNowDate("MM"),
						getNowDate("yyyy")));
				setBackgroundColorForButtons(v,
						getResources().getColor(R.color.normal_button),
						getResources().getColor(R.color.active_button));
				// v.setBackgroundColor(R.color.active_button);
			}
		});

		etMoney.setOnEditorActionListener(new EditText.OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				boolean handled = false;
				// // event.getKeyCode() == KeyEvent.KEYCODE_ENTER
				if (actionId == EditorInfo.IME_ACTION_NEXT
						|| actionId == EditorInfo.IME_ACTION_DONE) {
					// //&& event.getAction() == KeyEvent.ACTION_DOWN) {
					// // Handle pressing "Enter" key here
					addMoneyFromInput(db);
					handled = true;
				}
				return handled;
			}
		});
		addListview(db.getMoneyByDay(getNowDate("yyyy/MM/dd")));

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		overridePendingTransition(R.anim.activity_open_translate,
				R.anim.activity_close_scale);
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		// TODO Auto-generated method stub
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
				container_input.getWidth() - btnMoney.getWidth(),
				RelativeLayout.LayoutParams.WRAP_CONTENT);
		((RelativeLayout.MarginLayoutParams) params).setMargins(0,
				btnMoney.getWidth() / 6, 0, 0);
		etMoney.setLayoutParams(params);

		RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(
				container_buttons.getWidth() / 3 - 1,
				RelativeLayout.LayoutParams.WRAP_CONTENT);
		params2.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
		btnAll.setLayoutParams(params2);

		RelativeLayout.LayoutParams params3 = new RelativeLayout.LayoutParams(
				container_buttons.getWidth() / 3 - 1,
				RelativeLayout.LayoutParams.WRAP_CONTENT);
		((RelativeLayout.MarginLayoutParams) params3).setMargins(1, 0, 0, 0);
		params3.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
		btnMonthly.setLayoutParams(params3);

		RelativeLayout.LayoutParams params4 = new RelativeLayout.LayoutParams(
				container_buttons.getWidth() / 3,
				RelativeLayout.LayoutParams.WRAP_CONTENT);
		((RelativeLayout.MarginLayoutParams) params4).setMargins(1, 0, 0, 0);
		params4.addRule(RelativeLayout.RIGHT_OF, btnAll.getId());
		btnDaily.setLayoutParams(params4);
	}

	// private RelativeLayout.LayoutParams getParamsLayout(boolean setMargin){
	// if(setMargin==true){
	// ((RelativeLayout.MarginLayoutParams) params).setMargins(0,
	// btnMoney.getWidth() / 6, 0, 0);
	// }
	// return null;
	//
	// }
	private void addMoneyFromInput(DatabaseHandlerForApp db) {
		if (!checkEmptyEdittext(etMoney) && checkNumberInput(etMoney)) {
			Money m = new Money(Integer.parseInt(etMoney.getText().toString()),
					getNowDate("yyyy/MM/dd"));
			db.addMoney(m);
			etMoney.getText().clear();
			addListview(db.getAllMoney());
			Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_SHORT)
					.show();
		} else {
			Toast.makeText(getApplicationContext(), "Input a number, please",
					Toast.LENGTH_SHORT).show();
		}
	}

	private String getNowDate(String format_day) {
		DateFormat dateFormat = new SimpleDateFormat(format_day);
		Date date = new Date();
		return dateFormat.format(date);
	}

	private boolean checkEmptyEdittext(EditText et) {
		return et.getText().toString().trim().length() == 0;
	}

	private void addListview(ArrayList<Money> arr) {
		adapter = new ListviewAdapterCustom(this, arr);
		lvSubject.setAdapter(adapter);
	}

	private void setBackgroundColorForButtons(View v, int normal_color,
			int active_color) {
		btnAll.setBackgroundColor(normal_color);
		btnDaily.setBackgroundColor(normal_color);
		btnMonthly.setBackgroundColor(normal_color);
		v.setBackgroundColor(active_color);
	}

	// private int getItemHeightofListView(ListView listView, int items) {
	//
	// ListAdapter mAdapter = listView.getAdapter();
	//
	// int listviewElementsHeight = 0;
	// // for listview total item height
	// // items = mAdapter.getCount();
	//
	// for (int i = 0; i < items; i++) {
	//
	// View childView = mAdapter.getView(i, null, listView);
	// childView.measure(
	// MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
	// MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
	// listviewElementsHeight += childView.getMeasuredHeight();
	// }
	//
	// return listviewElementsHeight;
	//
	// }

	private boolean checkNumberInput(EditText et) {
		try {
			Integer.parseInt(et.getText().toString().trim());
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}
}
